package com.srv.persistence.impl.cloud;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.GetObjectRequest;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.srv.model.Resource;
import com.srv.persistence.PersistenceException;
import com.srv.Config;

/**
 * 运行object示例需要做如下几件事：
 * 1、获取accessId\accessKey，修改示例中对应accessId\accessKey
 * 2、修改需要上传的文件uploadFilePath，文件必须存在, 修改下载文件的路径downloadFilePath
 * 3、指定文件的显示名称objectName，指定bucketName
 * **/
public class AliyunOSS {
	private static Log log = LogFactory.getLog(AliyunOSS.class);    
    private final static String accessId = Config.aliyun_oss_accessId;
    private final static String accessKey = Config.aliyun_oss_accessKey;
    private final static String ossEndpoint = Config.aliyun_oss_ossEndpoint; 
    
    private final static String STR_t="t";	
    
    private final static String URI_PRI="oss://";
    
    
    /**
	    * 保存资源流.
	    * @param resource
	    * @param resourceName
	    * @return 
	    * "oss://85f01aeae2a448879dc7b3bfdc26f247/a.jpg"
	    * @throws java.io.IOException
	    */
	   public static String save(			   
			   Resource resource			   
			   ) throws PersistenceException{
		   try{
			   OSSClient client = new OSSClient(ossEndpoint, accessId, accessKey);
			   String theBucketName = resource.id;
			   if(!client.isBucketExist(theBucketName)){
				 client.createBucket(theBucketName);  
			   }
			   
			   ObjectMetadata objectMeta = new ObjectMetadata();	        		        
		       objectMeta.setContentLength(resource.content.length);
		       objectMeta.addUserMetadata(STR_t, String.valueOf(resource.contentType));	       		       
		        //上传文件
		        InputStream input = new ByteArrayInputStream(resource.content);
		        client.putObject(theBucketName, resource.name, input, objectMeta);
		        log.debug(AliyunOSS.URI_PRI.concat(theBucketName).concat("/").concat( resource.name));
		        return AliyunOSS.URI_PRI.concat(theBucketName).concat("/").concat( resource.name);
		   }catch(Exception e){
			   log.error("error:"+e.getMessage());
			   throw new PersistenceException();			 
		   }		   
	   }	   	   
	   /**
	    * 获取对象.
	    * @param resourceID
	    * @param resourceName
	    * @return
	    * 	object[]<br/>
	    *   object[0] is instance of InputStream<br/>
	    *   object[1] is instance of HashMap contain the key-value of the object's metadata
	    * @throws Exception
	    */
	   public static Resource getObject(
			   String resourceID,
			   String resourceName
	   )throws Exception{
		   OSSClient client = new OSSClient(ossEndpoint, accessId, accessKey);	        
	        //下载文件
		   OSSObject obj= client.getObject(new GetObjectRequest(resourceID, resourceName));
		   Resource r=new Resource();
		   r.id = resourceID;
		   r.name = resourceName;
		   ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		   int ch;
		   while ((ch = obj.getObjectContent().read()) != -1)
		   {
		       bytestream.write(ch);
		   }
		   r.content=bytestream.toByteArray();
		   bytestream.close();
		   r.contentType=Integer.parseInt(obj.getObjectMetadata().getUserMetadata().get(STR_t));
		   return r;
		         
	   }
	   public static void main(String[] args) throws Exception{
//		   String nodeID="15aa464160d74fe8b735096bcc31dd77";
//		   String resourceName="test1.jpg";
		   //getObject(null,resourceName,nodeID);
	   }
}
